layui.use(['form','jquery','layer','table','laydate','upload'],function () {
    var form = layui.form;
    var $ = layui.$;
    var layer = layui.layer;
    var table = layui.table;
    var laydate = layui.laydate;
    var upload = layui.upload;
    var zTree;
    var rMenu;
    var tableIns;

    $(document).click(function () {
        parent.$('.tab').hide();
    });
    getDepts();
    getDept();
    getUsersByAccountNameDeptNameRegisterDate();
    //注册时间渲染
    laydate.render({
        elem: '#registerDate',
        type: 'datetime'
    })
    //刷新按钮
    $('#refresh').click(function () {
        location.reload();
    });
    //返回按钮
    $('#goBack').click(function () {
        var iframe = parent.$('.iframe');
        $.each(iframe,function (i,item) {
            if('后台人员列表' == $(item).attr('_href')){
                parent.$('#beforeHref').val($(item).attr('_href'));
                parent.beforeHref();
                return;
            }
        });
    });

    //高级检索按钮
    $('#advancedSearch').click(function () {
        layer.open({
            type: 2,
            title: '高级检索',
            content: '/jurisdiction/backgroundPersonnelManagement/backstageStaff/user-advanced-search.html',
            area: ['700px', '500px'],
            offset: 'auto',
            shade: 0.4,

        })
    });
    //添加后台人员按钮
    addUser = function addUser(){
        parent.$('#quickEntry').val('添加后台人员');
        parent.quickEntry();
    }
    //搜索按钮
    form.on('submit(search)',function (obj) {
        getUsersByAccountNameDeptNameRegisterDate(obj.field);
        return false;
    })
    //查询所有部门
    function getDepts() {
        var setting = {
            data: {
                simpleData: {
                    enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                    idKey: "id",  //节点数据中保存唯一标识的属性名称
                    pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                    rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                },
                key: {
                    name: "deptName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                }
            },
            view: {
                dblClickExpand: false
            },
            check: {
                enable : false,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
                nocheckInherit:true  //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
            },
            callback: {
                onClick: zTreeOnClick,//点击树节点展示对应table信息
                onRightClick: OnRightClick
            }
        };

        $.ajax({
            url: '/SyDept/getDepts',
            type: 'post',
            dataType: 'json',
            success: function (data) {
                //部门树的渲染
                zTree = $.fn.zTree.init($("#deptTree"), setting, data.data);//初始化树
                zTree.expandAll(true);    //true 节点全部展开、false节点收缩
            }
        });

        rMenu = $("#rMenu");

        //点击节点
        function zTreeOnClick() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            if(!node.isParent){
                getUsersByDeptId(node.id);
            }else{
                layer.msg("请选择最小分类类别");
            }
        }
        //树的一系列配置
        function OnRightClick(event, treeId, treeNode) {
            if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                zTree.selectNode(treeNode);
                showRMenu("node", event.clientX, event.clientY);
            }
        }
        function showRMenu(type, x, y) {
            $("#rMenu ul").show();
            if (type=="root") {
                $("#m_del").hide();
            } else {
                $("#m_del").show();
            }

            y += document.body.scrollTop;
            x += document.body.scrollLeft;
            rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

            $("body").bind("mousedown", onBodyMouseDown);
        }
        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }
        function onBodyMouseDown(event){
            if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }
        //点击编辑部门后弹出弹出层
        editDeptTreeNode = function editDeptTreeNode() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            layer.prompt({
                title: '修改部门名称',
                value: node.deptName,
                area: ['300px', '100px']
            }, function(value, index, elem){
                updateDeptNameById(value,node.id);
                layer.close(index)
            });
        }
        //点击删除部门后弹出弹出层
        removeDeptTreeNode = function removeDeptTreeNode() {
            var nodes = zTree.getSelectedNodes();
            var node = nodes[0];
            var layerIndex = layer.confirm('确定要删除"' + node.deptName + '"么?', {
                btn: ['确定','取消']
            }, function(){
                deleteDeptById(node.id);
                layer.close(layerIndex);
            }, function(){
                layer.close(layerIndex);
            });
        }
    }
    //根据用户id查询后台人员表
    function getUsersByDeptId(id) {
        $.ajax({
            url: '/login/getUsersByDeptId',
            data: {deptId: id},
            dataType: 'json',
            success: function (data) {
                usersTable(data.data.data);
            }
        });
    }
    //根据用户账号、用户姓名、所属部门、注册日期查询后台人员表
    function getUsersByAccountNameDeptNameRegisterDate(params) {
        $.ajax({
            url: '/login/getUsersByAccountNameDeptNameRegisterDate',
            data: params,
            dataType: 'json',
            success: function (data) {
                usersTable(data.data.data);
            }
        });
    }
    //将查询出来的数据渲染到表中
    usersTable = function usersTable(data) {
        table.render({
            elem: '#backstageStaffTable',
            title: '后台管理员列表',
            data: data,
            toolbar: '#button_ids',
            page:{
                layout:['count','prev','page','next','limit','skip','refresh'],
                first:"首页",
                last:"尾页",
            },
            width:1350,
            cols: [[
                {type:'checkbox'},
                {field:"trueName",title:"用户姓名",align:'center',width:145},
                {field:"",title:"用户头像",align:'center',width:145,templet: function (data) {
                     return '<img src="'+ data.acatarUrl +'" />'
                }},
                {field:"sex",title:"性别",align:'center',width:145},
                {field:"account",title:"用户账号",align:'center',width:145},
                {field:"deptName",title:"所属部门",align:'center',width:145},
                {field:"enabled",title:"是否启用",width:145,align:'center',templet:function(data){
                    if(data.enabled == 1){
                        return '<input type=\"checkbox\" value="'+data.userId +'" lay-skin=\"switch\" lay-text=\"启用|停用"\ checked lay-filter="enableStatus">';
                    }else if(data.enabled == 2){
                        return '<input type=\"checkbox\" value="'+data.userId +'" lay-skin=\"switch\" lay-text=\"启用|停用"\ lay-filter="enableStatus">';
                    }
                }},
                {field:"status",title:"账号状态",width:145,align:'center',templet:function(data){
                    if(data.status == 1){
                        return '<input type=\"checkbox\" value="'+data.userId +'" lay-skin=\"switch\" lay-text=\"使用中|已封禁"\ checked lay-filter="userStatus">';
                    }else if(data.status == 2){
                        return '<input type=\"checkbox\" value="'+data.userId +'" lay-skin=\"switch\" lay-text=\"使用中|已封禁"\ lay-filter="userStatus">';
                    }else if(data.status == 3){
                        return '<input type=\"checkbox\" value="'+data.userId +'" lay-skin=\"switch\" lay-text=\"使用中|已封禁"\ lay-filter="userStatus">';
                    }else if(data.status == 4){
                        return '<input type=\"checkbox\" value="'+data.userId +'" lay-skin=\"switch\" lay-text=\"使用中|已封禁"\ lay-filter="userStatus">';
                    }
                }},
                {field:"registerDate",title:"注册时间",align:'center',width:145},
                {field:'',title:"操作",align:'center',width:145,toolbar: '#operation'}
            ]]
        });
        table.on('toolbar(backstageStaffTable)',function(obj){
            if(obj.event == 'importAdministrators'){
                layer.open({
                    type: 1,
                    title: "导入管理员",
                    content: $("#importExcel"),
                    offset: 'auto',
                    btn:['确定','取消'],
                    success: function (layero, inde) {
                        upload.render({
                            elem: '#importExcel',
                            url: '/login/importUser',
                            method: "post",
                            field: 'file',
                            accept: 'file',
                            exts: 'xlsx|xls',
                            done: function (res, index, upload) {
                                if(res.code == 0){
                                    layer.close(inde)
                                    getUsersByAccountNameDeptNameRegisterDate();
                                    layer.msg("导入成功");
                                }
                            }
                        });
                    }
                })

            }
        })
    }
    //开关事件 用户启用状态
    form.on('switch(enableStatus)',function (data) {
        if(data.elem.checked){
            updateUserEnable(data.value,1);
        }else{
            updateUserEnable(data.value,2);
        }
    });
    //开关事件 账号状态
    form.on('switch(userStatus)',function (userStatus) {
        if(userStatus.elem.checked ){
            updateUserEnable(userStatus.value,1);
            updateUserStatus(userStatus.value,1);
            deleteClosureUser(userStatus.value);
            addUnsealUser(userStatus.value);
        }else{
            updateUserEnable(userStatus.value,2);
            updateUserStatus(userStatus.value,4);
            addClosureUser(userStatus.value);
        }
    });
    //更改用户账号状态
    function updateUserStatus(id,status) {
        $.ajax({
            url: '/login/updateUserStatus',
            data: {
                userId: id,
                status: status
            },
            type: 'post',
            dataType: 'json',
            success: function (data) {
                getUsersByAccountNameDeptNameRegisterDate();
                if(status == 1){
                    layer.msg("账号可以使用");
                }else{
                    layer.msg("账号已封禁");
                }
            }
        });
    }
    //更改用户启用状态
    function updateUserEnable(id,status) {
        $.ajax({
            url: '/login/updateUserEnable',
            data: {
                userId: id,
                enabled: status
            },
            type: 'post',
            dataType: 'json',
            success: function (data) {
                if(status == 1){
                    layer.msg("启用成功")
                }else{
                    layer.msg("停用成功")
                }
            }
        });
    }
    //表格内点击事件
    table.on('tool(backstageStaffTable)',function (obj) {
        switch (obj.event) {
            case 'select' :
                selectBackstageStaffTable(obj);
                break;
            case 'compile' :
                updateUserMessage(obj);
                break;
            case 'closure' :
                closureUser(obj);
                break;
            case 'jurisdiction' :
                setJurisdiction(obj);
                break;
        }
    })
    //查看信息弹出层
    function selectBackstageStaffTable(obj) {
        layer.open({
            type: 2,
            title: '查看用户信息',
            area:["95%","99%"],
            scrollbar: false,
            offset:'auto',
            btn: ['确定','关闭'],
            content: '/jurisdiction/backgroundPersonnelManagement/backstageStaff/select-user-message.html',
            yes: function (index, layero) {
                layer.close(index);
            },
            success: function (layero, index) {
                var childHtml = layero.find('iframe').contents();
                var user = obj.data;
                childHtml.find('#acatarUrl').attr('src',user.acatarUrl);
                childHtml.find('.trueName').text(user.trueName);
                childHtml.find('#account').text(user.account);
                childHtml.find('#trueName').text(user.trueName);
                childHtml.find('#sex').text(user.sex);
                childHtml.find('#phone').text(user.phone);
                childHtml.find('#idCard').text(user.idCard);
                childHtml.find('#birthDate').text(user.birthDate);
                childHtml.find('#deptName').text(user.deptName);
                childHtml.find('#registerTime').text(user.registerDate);
                childHtml.find('#email').text(user.email);
                childHtml.find('#freestyle').text(user.freestyle);
                if(user.registerIp == ''){
                    user.registerIp = '无';
                }
                childHtml.find('#registerIp').text(user.registerIp);
            }
        })
    }
    //修改部门名称
    function updateDeptNameById(deptName,id) {
        $.ajax({
            url: '/SyDept/updateDeptNameById',
            type: 'post',
            dataType: 'json',
            data: {
                deptName: deptName,
                id: id
            },
            success: function (data) {
                getDepts();
                getUsersByAccountNameDeptNameRegisterDate();
                layer.msg(data.data);
            }
        })
    }
    //根据id删除部门
    function deleteDeptById(id) {
        $.ajax({
            url: '/SyDept/deleteDeptById',
            data:{id: id},
            dataType: 'json',
            success: function (data) {
                getDepts();
                getUsersByAccountNameDeptNameRegisterDate();
                layer.msg(data.data);
            }
        });
    }
    //修改用户信息
    function updateUserMessage(obj) {
        layer.open({
            type: 2,
            title: '修改用户信息',
            area: ['1200px', '675px'],
            offset: 'auto',
            shade: 0.4,
            content: '/jurisdiction/backgroundPersonnelManagement/backstageStaff/update-user-message.html',
            success: function (layero, index) {
                var childHtml = layero.find('iframe').contents();
                var user = obj.data;
                childHtml.find('#acatarUrl').attr('src',user.acatarUrl);
                childHtml.find('.trueName').text(user.trueName);
                childHtml.find('#account').val(user.account);
                childHtml.find('#trueName').val(user.trueName);
                childHtml.find('#sex').val(user.sex);
                childHtml.find('#phone').val(user.phone);
                childHtml.find('#idCard').val(user.idCard);
                childHtml.find('#birthDate').val(user.birthDate);
                childHtml.find('#registerDate').val(user.registerDate);
                childHtml.find('#registerIp').val(user.registerIp);
                childHtml.find('#email').val(user.email);
                childHtml.find('#freestyle').val(user.freestyle);
                childHtml.find('#userId').val(user.userId);
                childHtml.find('#dept').val(user.deptId);
            },
            end:function () {
                getUsersByAccountNameDeptNameRegisterDate();
            }
        })
    }
    function closureUser(obj) {
        var user = obj.data;
        if(4 == user.status){
            layer.msg('此用户已被封禁');
        }else{
            layer.open({
                type: 2,
                title: '封停用户',
                area: ['700px', '400px'],
                offset: 'auto',
                shade: 0.4,
                content: '/jurisdiction/backgroundPersonnelManagement/backstageStaff/closure-user.html',
                success: function (layero, index) {
                    var childHtml = layero.find('iframe').contents();
                    childHtml.find('#account').val(user.account);
                    childHtml.find('#userId').val(user.userId);
                },
                end: function () {
                    getUsersByAccountNameDeptNameRegisterDate();
                }
            })
        }
    }
    //权限按钮
    function setJurisdiction(obj) {
        layer.open({
            type: 2,
            title: '设置权限',
            area: ['700px', '400px'],
            offset: 'auto',
            shade: 0.4,
            content: '/jurisdiction/backgroundPersonnelManagement/backstageStaff/set-jurisdiction.html',
            success: function (layero, index) {
                var user = obj.data;
                var childHtml = layero.find('iframe').contents();
                childHtml.find('#account').val(user.account);
                childHtml.find('#remark').val(user.remark);
                childHtml.find('#userId').val(user.userId);
            },
            end: function () {
                getUsersByAccountNameDeptNameRegisterDate();
            }
        })

    }
    //获取 年月日 时分秒 星期
    function setTime(){
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var today = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        //当小时小于10时进行补零
        var currentTime = zeroFill(year) + '-' + zeroFill(month) + '-' + zeroFill(today) +  ' ' + zeroFill(hour) + ':' + zeroFill(minute) + ':' + zeroFill(second);
        return currentTime;
    }
    //补零
    function zeroFill(time){
        if(time < 10){
            time = '0' + time;
        }
        return time;
    }
    //添加封禁记录
    function addClosureUser(userId) {
        $.ajax({
            url: '/JsClosure/addClosureUser',
            type: 'post',
            data: {
                userId: userId,
                type: 3,
                startDate: setTime(),
                days: 36500
            },
            dataType: 'json',
            success: function (data) {

            }
        });
    }
    //删除封禁记录
    function deleteClosureUser(userId) {
        $.ajax({
            url: '/JsClosure/deleteClosureUser',
            data: {
                userId: userId
            },
            dataType: 'json',
            success: function (data) {

            }
        })
    }
    //添加解封记录
    function addUnsealUser(id) {
        $.ajax({
            url: '/JsUnseal/addUnsealUser',
            type: 'post',
            data: {
                userCode: id,
                type: 3,
                days: 36500
            },
            dataType: 'json',
            success: function (data) {

            }
        });
    }
    function getDept() {
        $.ajax({
            url: '/SyDept/getDepts',
            type: 'post',
            dataType: 'json',
            success: function (data) {
                var option = data.data;
                var deptId = $('#dept').val();
                for (var i = 0; i < option.length; i++) {
                    if(option[i].id != 0){
                        $('#deptId').append('<option value="' + option[i].id + '">' + option[i].deptName + '</option>');
                    }
                }
                $('#deptId').val(deptId);
                form.render();
            }
        });
    }
    //返回按钮
    $('#goBack').click(function () {
        var iframe = parent.$('.iframe');
        $.each(iframe,function (i,item) {
            if('后台用户列表' == $(item).attr('_href')){
                parent.$('#beforeHref').val($(item).attr('_href'));
                parent.beforeHref();
            }
        });
    });
})